package com.api.oa.utils;


import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.date.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

public class LocalRedis {


    ValueOperations<String, Object> redis;

    TimedCache<String, Object> timedCache = new TimedCache<String, Object>(1000 * 3);


    private boolean isClosed;

    public LocalRedis(ValueOperations<String, Object> valueOperations, boolean closed) {

    }

    public LocalRedis(ValueOperations<String, Object> valueOperations, RedisConnectionFactory redisConnectionFactory) {
        this.redis = valueOperations;
        timedCache.schedulePrune(1000 * 10);
        try {
            RedisConnection connection = redisConnectionFactory.getConnection();
            this.isClosed = connection.isClosed();
        } catch (Exception e) {
            this.isClosed = false;
        }

    }

    public void set(String key, Object value, long timeout) {


        try {
            if (isClosed) {
                timedCache.put(key, value, timeout);
            } else {
                redis.set(key, value, timeout);
            }
        } catch (Exception e) {
            timedCache.put(key, value, timeout);
        }

    }

    public Object get(String key) {
        try {
            return isClosed ? timedCache.get(key) : redis.get(key);
        } catch (Exception e) {
            return timedCache.get(key);
        }

    }


    //启动定时任务，每4秒检查一次过期


}
